package com.vim.modules.web.controller;

import com.vim.common.model.response.Response;
import com.vim.common.model.response.RestfulResponse;
import com.vim.common.utils.ValidateUtils;
import com.vim.modules.web.model.Table;
import com.vim.modules.web.model.TableDTO;
import com.vim.modules.web.service.GenService;
import com.vim.modules.web.utils.CreateJava;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 自动代码生成
 */
@RestController
public class CodeController {

    @Value("${dataSource.dbName}")
    private String dbName;

    @Resource
    private GenService genService;

    /**
     * 数据库信息
     */
    @RequestMapping(value = "/dbInfo")
    public RestfulResponse dbInfo(){
        Map<String,Object> result = new HashMap<>();
        List<String> tableList = genService.findTableList();
        result.put("dbName", dbName);
        result.put("dbTable", tableList);
        return new RestfulResponse(result);
    }

    /**
     * 数据表信息
     */
    @RequestMapping(value = "/tableInfo")
    public RestfulResponse tableInfo(@RequestParam(value = "tableName") String tableName){
        ValidateUtils.checkNotBlank(tableName);
        TableDTO dto = new TableDTO();
        dto.setDbName(dbName);
        dto.setTableName(tableName);
        return new RestfulResponse(genService.findTableColumnList(dto));
    }

    /**
     * 代码生成
     */
    @RequestMapping(value = "/code",method = RequestMethod.POST)
    public RestfulResponse code(@RequestParam(value = "outputPath") String outputPath,
                                @RequestParam(value = "dbName") String dbName,
                                @RequestParam(value = "tableName") String tableName){
        ValidateUtils.checkNotBlank(outputPath);
        ValidateUtils.checkNotBlank(dbName);
        ValidateUtils.checkNotBlank(tableName);
        TableDTO dto = new TableDTO();
        dto.setOutputPath(outputPath);
        dto.setPackagePath("com.vim.modules.web");
        dto.setDbName(dbName);
        dto.setTableName(tableName);
        Table table = genService.findTableColumnList(dto);

        //生成文件
        CreateJava java = CreateJava.getInstance();
        java.createDictory(dto.getOutputPath(),dto.getPackagePath());
        java.createFile(table);

        return new RestfulResponse(Response.OK);
    }
}
